package top.lenjon.autodeploy;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Objects;

@RestController
@SpringBootApplication
public class AutodeployApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(AutodeployApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(AutodeployApplication.class, args);
    }


    private static void delete(File file) {
        Objects.requireNonNull(file);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            int n = files == null ? 0 : files.length;
            for (int i = 0; i < n; i++) {
                delete(files[i]);
            }
        }
        LOGGER.info("删除" + file.getName());
        file.delete();
    }


    @PostMapping("/")
    public String upload(@RequestParam(value = "file") MultipartFile multipartFile,
                         @RequestParam(value = "path") String dirname) {
        String fileName = multipartFile.getOriginalFilename();
        Objects.requireNonNull(fileName);
        String suffix = fileName.substring(fileName.lastIndexOf(".")).replace(".", "");
        if (!"zip".equals(suffix)) {
            return "only allow zip file";
        }
        if (dirname == null || "".equals(dirname)) {
            return "禁止使用根目录";
        }
        File dir = new File(dirname);
        if (dir.exists()) {
            delete(dir);
        }
        if (!dir.mkdirs()) {
            return "make dir fail";
        }
        File zip = new File(dir.getAbsolutePath(), fileName);

        try {
            String destDirPath = dir.getAbsolutePath();
            multipartFile.transferTo(zip);
            ZipFile zipFile = new ZipFile(zip);
            Enumeration<?> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                LOGGER.info(String.format("解压 %s", entry.getName()));
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File _dir = new File(dirPath);
                    if (_dir.exists() || !_dir.mkdirs()) {
                        return "error make dir";
                    }
                } else {
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    if(targetFile.getAbsolutePath().contains("__MACOSX")){
                        continue;
                    }
                    if (!targetFile.getParentFile().exists()) {
                        return "no parent file dir：fileName: " + targetFile.getAbsolutePath();
                    }
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.close();
                    is.close();
                }
            }
            zipFile.close();
            zip.delete();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return "ok";
    }
}
